from flask import g
from flask import session, jsonify,request


from info.models import User, News, Category
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import index_blue
from flask import render_template, current_app


#功能描述: 获取首页新闻内容
# 请求路径: /newslist
# 请求方式: GET
# 请求参数: cid,page,per_page
# 返回值: data数据
@index_blue.route('/newslist')
@user_login_data
def news_list():
    """
        1. 获取参数
        2. 参数类型转换
        3. 分页查询
        4. 获取分页对象属性,总页数,当前页,当前页对象
        5. 将当前页对象列表,转成字典列表
        6. 响应,返回json数据
        :return:
        """
    # 1. 获取参数
    #新闻分类编号
    cid = request.args.get('cid','1')#如果获取不到,使用后面的默认值
    # 第几页
    page = request.args.get("page","1")
    # 每页几条
    per_page = request.args.get("per_page", "10")
    # 2. 参数类型转换,为了paginate准备
    try:
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        page = 1
        per_page = 10
    # 3. 分页查询
    try:
        filters = []
        if cid != "1":
            filters.append(News.category_id == cid)

                                          #分类id
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,per_page,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="分页获取失败")

    """
    paginate.items: 表示当前页的所有对象
    paginate.pages: 总页数
    paginate.page :当前页

    """

    # 4. 获取分页对象属性,总页数,当前页,当前页对象

    totalPage = paginate.pages
    currentPage = paginate.page
    items = paginate.items
    # 5. 将当前页对象列表,转成字典列表
    newsList = []
    for item in items:
        newsList.append(item.to_dict())
    # 6. 响应,返回json数据
    return jsonify(errno=RET.OK, errmsg="获取成功", totalPage=totalPage, currentPage=currentPage, newsList=newsList)




# XUJvdgQO8zn4LkljWxbEDThS', '6CY9', b'\xff\xd8\x

@index_blue.route('/')
@user_login_data
def show_index():
    # 获取用户的编号,从session
    # user_id = session.get("user_id")
    #
    # # 判断用户是否存在
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)

    # 查询数据库,根据点击量查询前十条新闻
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(10).all()

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询新闻异常")

    # 将新闻对象列表, 转成字典列表
    click_new_list = []  # [{ob1},{ob2},{ob3}]

    # [ob1,ob2,ob3}
    for news in news_list:
        # new1=oc1
        # new2=ob2
        click_new_list.append(news.to_dict())

    # 查询所有的分类信息
    try:  # categories
        categories = Category.query.all()  # [o1.o2,o3]
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="分类查询失败")

    # 将分类的对象列表,转成字典列表
    category_list = []
    # {o1}          # [o1.o2,o3]
    for category in categories:
        category_list.append(category.to_dict())

    # 将用户的信息转成字典
    dict_data = {
        # 如果user存在,返回左边, 否则返回右边
        "user_info": g.user.to_dict() if g.user else "",
        "click_news_list": click_new_list,
        "categories": category_list

        # '[{ob1},{ob2},{ob3}]':[{ob1},{ob2},{ob3}]
    }

    return render_template("news/index.html", data=dict_data)


@index_blue.route("/favicon.ico")
def weblogo():
    return current_app.send_static_file("news/favicon.ico")
